<?php
namespace app\order\controller;

use think\Controller;
use think\Db;
use app\order\model\OrderModel;
use app\food\model\FoodModel;

class Apis extends Controller
{

    public function addOrder($order)
    {
        //极光推送
        $app_key = "5f34b1b8dae026d52c202536";
        $master_secret = "210d8a6d6b3b30af464e93d1";
        $client = new \JPush\Client($app_key, $master_secret);
        $res = $client->push()
            ->setPlatform('all')
            ->addAllAudience()
            ->setNotificationAlert('您有新的订单')
            ->send();


        $order['order_ctime'] = date('Y-m-d H:i:s', time());
        $order['order_status'] = 0;
        $order['food_id'] = json_encode($order['food_id']);
        $OrderModel = new OrderModel();
        $res = $OrderModel->addOrder($order);
        return json($res);
    }

    public function delOrderById($id)
    {
        $OrderModel = new OrderModel();
        $res = $OrderModel->delOrder($id);
        return json($res);
    }

    public function upOrderById($order)
    {
        $order['order_utime'] = date('Y-m-d H:i:s', time());
        $OrderModel = new OrderModel();
        $res = $OrderModel->upOrder($order);
        return json($res);
    }

    public function upOrderStatusByIds($ids, $status)
    {
        $OrderModel = new OrderModel();
        $res = $OrderModel->upOrderStatus($ids, $status);
        return json($res);
    }

    public function getAllOrder($order)
    {
        $OrderModel = new OrderModel();
        $FoodModel = new FoodModel();
        $foods = $FoodModel->getFood(null);
        $orders = $OrderModel->getOrder($order);
        foreach ($orders as $index => $order) {
            $list = json_decode($order['food_id'], true);
            $orders[$index]['order_obj'] = $list;
            $detail = $list['list'];
            if (is_array($detail)) {
                $keys = array_keys($detail);
                $listContent = "总金额：" . $list['total'] . '元<br>';
                foreach ($keys as $key) {
                    $name = '';
                    foreach ($foods as $food) {
                        if ($food['food_id'] == $key) {
                            $name = $food['food_name'] . '  ¥' . $food['food_price'];
                        }
                    }
                    $listContent = $listContent . $name . '×' . $detail[$key] . "<br>";
                }
                $orders[$index]['order_list'] = $listContent;
            }
        }
//        dump($orders);
//        die;
        return json($orders);
    }

    public function getOrderByApp($app)
    {
        $order['order_app'] = $app;
        return $this->getAllOrder($order);
    }

    public function getOrderByPhone($phone)
    {
        $order['order_phone'] = $phone;
        return $this->getAllOrder($order);
    }

}
